package com.niwodai.zhongkun.adapt.nyxj.async;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.nbopen.api.NBOpenSDK;
import com.niwodai.zhongkun.mapper.ZkLoanMapper;
import com.niwodai.zhongkun.model.adapt.nyxj.req.NYXJLoanQueryReq;
import com.niwodai.zhongkun.model.core.LoanResultQueryResp;
import com.niwodai.zhongkun.model.entity.ZkLoan;
import com.niwodai.zhongkun.model.enums.StateEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Objects;

/**
 * @Author syh
 * @date 2025/6/17
 * 异步轮询服务
 */
@Service
@Slf4j
public class AsyncPollService {

    @Resource
    private ZkLoanMapper zkLoanMapper;

    @Async("noticeTaskExecutor") // 使用指定的线程池
    public void pollOperateAsync(ZkLoan loan, NYXJLoanQueryReq nyxjLoanQueryReq) {
        try {
            //判断zk_loan的放款状态是否为终态，为终态，就不发起异步任务
            ZkLoan zkLoanInfo = zkLoanMapper.selectLoanInfoByParam(loan.getOutOrderNo());
            //直接返回
            if (!Objects.equals(zkLoanInfo.getLoanState(), StateEnum.LOAN_PROGRESS.key)) {
                log.info("【放款状态已达到终态】loan_id: {}", loan.getOutOrderNo());
                return;
            }
            log.info("【开始异步轮询】loan_id: {}", loan.getOutOrderNo());
            long startTime = System.currentTimeMillis(); // 记录开始时间
            int interval = 120; // 每隔120秒查询一次
            int timeoutSeconds = 1500;   // 25分钟超时（单位：秒）
            String requestJson = JSONObject.toJSONString(nyxjLoanQueryReq);     // 缓存请求体，避免重复序列化
            log.info("【还款结果查询<<轮询操作>>请求的参数】==>>> : {}", requestJson);
            while (true) {
                long elapsedTime = (System.currentTimeMillis() - startTime) / 1000;
                if (elapsedTime >= timeoutSeconds) {
                    log.warn("【放款结果轮询超时】已达 {} 秒，停止重试", timeoutSeconds);
                    break;
                }
                try {
                    String loanResultInterval = NBOpenSDK.send("", "loanResultQueryZHONGKUN", requestJson);
                    log.info("【还款结果查询<<轮询操作>>loanId: {},结束返回】==>>> : {}", nyxjLoanQueryReq.getLoan_id(), loanResultInterval);

                    JSONObject jsonLoanObjectInterval = JSONObject.parseObject(loanResultInterval);
                    JSONObject dataObj = jsonLoanObjectInterval.getJSONObject("Data");
                    if (dataObj == null) {
                        log.warn("【放款结果返回的Data字段为空】响应内容不合法");
                        Thread.sleep(interval * 1000L);
                        continue;
                    }
                    LoanResultQueryResp loanRespInterval = dataObj.toJavaObject(LoanResultQueryResp.class);
                    if (!Objects.equals(loanRespInterval.getStatus(), Integer.valueOf(StateEnum.LOAN_PROGRESS.key))) {
                        // 状态不是放款中，说明已达到终态，更新状态并退出
                        if (Objects.equals(loanRespInterval.getStatus(), Integer.valueOf(StateEnum.LOAN_SUCCESS.key)) || Objects.equals(loanRespInterval.getStatus(),
                                Integer.valueOf(StateEnum.LOAN_ERROR.key))) {
                            // 假设1为放款成功，-2为放款失败
                            loan.setLoanState(String.valueOf(loanRespInterval.getStatus()));
                            zkLoanMapper.updateById(loan);
                        }
                        break;
                    }
                    Thread.sleep(interval * 1000L); // 等待指定间隔
                } catch (JSONException e) {
                    log.error("JSON解析异常", e);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    log.error("线程中断异常", e);
                    break;
                }
            }
        } catch (Exception e) {
            log.error("【异步轮询发生异常】loan_id: {}", loan.getOutOrderNo(), e);
        }
    }

}
